package shaopeng.tank;

import java.awt.*;
import java.awt.event.KeyEvent;

public class Tank {

    private int x,y;

    //方向
    private Dir dir;

    private Boolean stop=true;

    private boolean bL,bU,bR,bD;

    public static final int SPEED=5;


    // 记录键盘是否被按下的变量

    public Tank(int x, int y,Dir dir) {
        this.dir=dir;
        this.x = x;
        this.y = y;
    }


    public void paint(Graphics g) {

        g.fillRect(x,y,50,50);
        move();
    }

    public void keyPressed(KeyEvent e) {
        //键盘事件获取那个键让按下
        int key = e.getKeyCode();
        switch (key) {
            case KeyEvent.VK_RIGHT:
                bR=true;
                break;
            case KeyEvent.VK_LEFT:
                bL=true;
                break;
            case KeyEvent.VK_UP:
                bU=true;
                break;
            case KeyEvent.VK_DOWN:
                bD=true;
                break;
        }
       setMainDir();
    }

    private void setMainDir() {
        if(!bL&&!bR&&!bU&&!bD){
            stop=true;
        }
        if(bL&&!bR&&!bU&&!bD){
            stop=false;
            dir=Dir.L;
        }
        if(!bL&&bR&&!bU&&!bD){
            stop=false;
            dir=Dir.R;
        }
        if(!bL&&!bR&&bU&&!bD){
            stop=false;
            dir=Dir.U;
        }
        if(!bL&&!bR&&!bU&&bD){
            stop=false;
            dir=Dir.D;
        }
    }

    private void move() {
        switch (dir) {
            case L:
                if(!stop){
                    x -= SPEED;
                }
                break;
            case U:
                if(!stop) {
                    y -= SPEED;
                }
                break;
            case R:
                if(!stop) {
                    x += SPEED;
                }
                break;
            case D:
                if(!stop) {
                    y += SPEED;
                }
                break;
        }

    }

    public void keyReleased(KeyEvent e) {
        //键盘事件获取那个键让按下
        int key = e.getKeyCode();
        switch (key) {
            case KeyEvent.VK_RIGHT:
                bR=false;
                break;
            case KeyEvent.VK_LEFT:
                bL=false;
                break;
            case KeyEvent.VK_UP:
                bU=false;
                break;
            case KeyEvent.VK_DOWN:
                bD=false;
                break;
        }

        setMainDir();
    }
}
